﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace One.Framework.UI.Security
{
    public class FormAuthentication
    {
        /// <summary>
        /// 로그인 사용자 보유권한정보 쿠키인증티켓 발행
        /// </summary>
        /// <param name="userId">사용자아이디</param>
        /// <param name="userData">보유권한그룹정보배열(EX)A,B,C)</param>
        /// <param name="domain">도메인</param>
        public static void SetTicket(string userId, string userData, string domain)
        {
            System.Web.Configuration.AuthenticationSection authen = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,													// Ticket version
                userId,											// Login ID associated with ticket
                DateTime.Now,										// Date/time issued 
                DateTime.Now.AddMinutes(int.Parse(authen.Forms.Timeout.TotalMinutes.ToString())),						// Date/time to expire
                false,												// "true" for a persistent user cookie
                userData,											// User-data, in this case the roles
                FormsAuthentication.FormsCookiePath					// Path cookie valid for
                );

            // Encrypt the cookie using the machine key for secure transport
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

            // Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            if (!string.IsNullOrWhiteSpace(domain))
                cookie.Domain = domain;

            // Add the cookie to the list for outgoing response    
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
